//
//  ProjectDetailChartViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/8/22.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

import UIKit

import Charts

class ProjectDetailChartViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource {
    
    var ifcaigou = false
    
    var numberofrows: Int{
        get{
            return self.showeddatas.count
        }
    }
    
    var candetail = false
    
    @IBOutlet weak var tableheight: NSLayoutConstraint!
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return numberofrows
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if let cel = cell as? SeparatorCell {
            if self.showeddatas.count > indexPath.row {
                
                cel.companyNameLbl.text = self.showeddatas[indexPath.row].1
                cel.countLbl.text = self.showeddatas[indexPath.row].2
                if indexPath.row == 0 {
                    cel.enterImg.isHidden = true
                } else {
                    if self.candetail == true {
                        if (Double(self.showeddatas[indexPath.row].2) ?? 0) > 0{
                            cel.enterImg.isHidden = false
                        } else {
                            cel.enterImg.isHidden = false
                        }
                    } else {
                        cel.enterImg.isHidden = true
                    }
                }
            }
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if candetail == true {
            if self.showeddatas.count > indexPath.row {
                let val = self.numdatas[indexPath.row].2
                if val > 0 {
                    if self.showeddatas.count > indexPath.row {
                        let canenter = candetail
                        if canenter == true {
                            if ifcaigou == true {
                                let list = PurchaseContactTableViewController()
                                list.title = "采购联系单列表"
                                if indexPath.row != self.numdatas.count - 1 {
                                    list.orgCode = self.showeddatas[indexPath.row].0
                                } else {
                                    list.orgCode = "x"
                                }
                                self.push(destination: list)
                            } else {
                                let list = ContractListViewController()
                                list.title = "合同档案列表"
                                if indexPath.row != self.numdatas.count - 1 {
                                    list.orgCode = self.showeddatas[indexPath.row].0
                                } else {
                                    list.orgCode = "x"
                                }
                                
                                self.push(destination: list)
                            }
                        }
                    }
                    
                }
            }
        }
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return tableView.dequeueReusableCell(withIdentifier: "SeparatorCell")!
    }
    
    @IBOutlet weak var scroll: UIScrollView!
    
    var key = ""
    
    @IBAction func showPicker(_ sender: Any) {
        load(with: "GetOrg")
    }
    
    var detailPath: String = StasticChartData
    
    var companys: Array<JSON> = []
    
    var selectedCompany:String = ""
    
    @IBOutlet weak var companyField: UITextField!
    
    @IBOutlet weak var moneyLabel: UILabel!
    
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var barChartView: BarChartView!
    
    var needshows: [String] = []
    
    var showeddatas: [(String,String,String)] = []
    
    let datePicker = UIDatePicker(frame: CGRect.init(origin: CGPoint.zero, size: CGSize(width: UIScreen.main.bounds.size.width, height: 220)))
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        showeddatas.append(("","部门","金额(万元)"))
        self.tableView.layer.cornerRadius = 3
        self.tableView.layer.borderColor = UIColor.hex("eeeeee").cgColor
        self.tableView.layer.borderWidth = 0.5
        configBarChart()
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.separatorColor = UIColor.hex("eeeeee")
        self.tableView.separatorInset = UIEdgeInsets.zero
        self.tableView.register(UINib.init(nibName: "SeparatorCell", bundle: Bundle.main), forCellReuseIdentifier: "SeparatorCell")
        for item in self.companys {
            if item.contents?["code"]?.rawString() == selectedCompany {
                self.companyField.text = item.contents?["name"]?.rawString()
            }
        }
//        datePicker.locale = Locale.init(identifier: "zh_CN")
//        datePicker.backgroundColor = UIColor.white
//        datePicker.datePickerMode = .date
//        datePicker.date = Date()
//        self.dateField.inputView = datePicker
//        self.dateField.inputAccessoryView = self.toolbarview
        load(with: "Detail")
    }
    
    override func endedit() {
        super.endedit()
        self.load(with: "Detail")
    }
    
    
    
    var selectedDate: String = ""
    
    @IBOutlet weak var dateField: UITextField!
    
    
    func configBarChart() -> Void {
        
        barChartView.backgroundColor = UIColor.white
        
        barChartView.legend.enabled = false
        
        barChartView.chartDescription?.enabled = false
        
        barChartView.noDataText = "暂无数据"
        
        barChartView.scaleYEnabled = false
        
        barChartView.doubleTapToZoomEnabled = false
        
        barChartView.dragEnabled = false
        
        barChartView.dragDecelerationEnabled = false
        
        barChartView.dragDecelerationFrictionCoef = 0.9
        
        barChartView.rightAxis.enabled = false
        
        barChartView.setExtraOffsets(left: 0, top: 30, right: 0, bottom: 30)
        
        let leftAxis = barChartView.leftAxis
        
        leftAxis.axisMinimum = 0.0
        
        leftAxis.labelPosition = .outsideChart
        
        leftAxis.labelCount = 5
        
        leftAxis.axisLineColor = .hex("666666")
        
        leftAxis.gridAntialiasEnabled = true
        
        leftAxis.valueFormatter = SymbolsValueFormatter()
        
        let xAxis = barChartView.xAxis
        
        xAxis.labelPosition = .bottom
        
        xAxis.drawGridLinesEnabled = false
        
        xAxis.axisLineWidth = 1
        
        barChartView.maxVisibleCount = 999
        
        barChartView.xAxis.valueFormatter = DateValueFormatter()
        
        barChartView.legend.enabled = false
        
        barChartView.drawMarkers = true
        
        let marker = BarMarker(color: UIColor(white: 0, alpha: 0.7), font: .systemFont(ofSize: 12), textColor: .white, insets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10))
        
        marker.chartView = barChartView
        
        marker.minimumSize = CGSize(width: 80, height: 40)
        
        barChartView.marker = marker
        
        barChartView.setExtraOffsets(left: 0, top: 30, right: 0, bottom: 30)
        
        barChartView.chartDescription = Description.init()
        
        barChartView.chartDescription!.text = "(万元)"
        
        barChartView.chartDescription!.font = UIFont.systemFont(ofSize: 14)
        
        barChartView.chartDescription!.position = CGPoint(x: 50, y: 10)
        
        barChartView.animate(yAxisDuration: TimeInterval.init(1.0))
    }
    
    func configLineChart() -> Void {
        
    }
    
    func loadBarData(array: Array<Double>) -> Void {
        
        var totalValue = 0.00
        
        for val in array {
            
            totalValue += val
            
        }
        
        var values: Array<BarChartDataEntry> = []
        
        for i in 0 ..< array.count {
            
            let data = BarChartDataEntry(x: Double(i), y: array[i])
            
            values.append(data)
        }
        
        let set1 = BarChartDataSet(values: values, label: nil)
        
        set1.drawValuesEnabled = false
        
        set1.colors = [UIColor.hex("35cf79")]
        
        let data = BarChartData.init(dataSets: [set1])
        
        data.barWidth = 0.5
        
        barChartView.data = data
        
        barChartView.xAxis.labelCount = values.count
        
    barChartView.setVisibleXRangeMaximum(Double(values.count))
        
    }

    func loadLineData(array: Array<Double>) -> Void {
        
        var values: Array<ChartDataEntry> = []
        
        for i in 0 ..< array.count {
            
            let total = array[0 ... i].reduce(0) { $0 + $1
            }
            
            let data = ChartDataEntry(x: Double(i), y: total)

            values.append(data)
        }
        
    }
    
    @IBAction func yunweiaction(_ sender: Any) {
        if rightbtns[0].isHidden == false {
            let list = ContractListViewController()
            list.title = "合同档案列表"
            list.orgCode = "x11x"
            self.push(destination: list)
        }
    }
    
    @IBAction func infoaction(_ sender: Any) {
        if rightbtns[1].isHidden == false {
            let list = ContractListViewController()
            list.title = "合同档案列表"
            list.orgCode = "x12x"
            self.push(destination: list)
        }
    }
    @IBAction func dataaction(_ sender: Any) {
        if rightbtns[2].isHidden == false {
            let list = ContractListViewController()
            list.title = "合同档案列表"
            list.orgCode = "x13x"
            self.push(destination: list)
        }
    }
    @IBAction func doubleaction(_ sender: Any) {
        if rightbtns[3].isHidden == false {
            let list = ContractListViewController()
            list.title = "合同档案列表"
            list.orgCode = "x15x"
            self.push(destination: list)
        }
    }
    @IBAction func totalaction(_ sender: Any) {
        if rightbtns[4].isHidden == false {
            let list = ContractListViewController()
            list.title = "合同档案列表"
            self.push(destination: list)
        }
    }
    @IBOutlet var rightbtns: [UIButton]!
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    var numdatas: [(String,String,Int)] = []
    override func success(for name: String) -> NetSuccess{
        func getOrgSuc(json: JSON)->Void{
            if json.contents?["success"]?.bool == true {
                if let data = json.contents?["data"]?.array {
                    companys = data
                    popalert()
                }
            }
        }
        
        func detail(json: JSON)->Void{
            
            if json.contents?["success"]?.bool == true {
                if let data = json.contents?["data"]?.contents {
                    
                    if ifcaigou == true {
                        self.numdatas = [("","",0)]
                        self.showeddatas = [("","部门","金额(万元)")]
                        if let list = data["list"]?.array {
                            let datas = list.map { (json) -> (String,String,String) in
                                let yearCount = (json.contents?["yearCount"]?.int ?? 0) / 1000000
                                let code = json.contents?["orgCode"]?.rawString() ?? ""
                                let name = json.contents?["typeTitle"]?.rawString() ?? ""
                                return (code,name,String(yearCount).rmbformat)
                            }
                            let total = list.reduce(0) { (result, json) -> Int in
                                return result + ((json.contents?["yearCount"]?.int ?? 0) / 1000000)
                            }
                            self.moneyLabel.text = String(total) + "万元"
                            self.showeddatas.append(contentsOf: datas)
                            self.numdatas.append(contentsOf: list.map({ (json) -> (String,String,Int) in
                                let yearCount = (json.contents?["yearCount"]?.int ?? 0)
                                let code = json.contents?["orgCode"]?.rawString() ?? ""
                                let name = json.contents?["typeTitle"]?.rawString() ?? ""
                                return (code,name,yearCount)
                            }))
                            if User.isLeader == true {
                                self.showeddatas.append(("","合计",String(total)))
                                self.numdatas.append(("","合计",total))
                            }
                            var doubleArr: Array<Double> = []
                            let arr = data["xxx"]?.array ?? []
                            for i in arr {
                                if let val = i.int {
                                    let value = Double(val) / 1000000
                                    doubleArr.append(value)
                                }
                            }
                            loadBarData(array: doubleArr)
                            self.tableheight.constant = CGFloat(40 * self.showeddatas.count + 20)
                            self.tableView.reloadData()
                        }
                    } else {
                        self.numdatas = []
                        self.showeddatas = [("","部门","金额(万元)")]
                        var showedcompanys: [JSON] = []
                        if User.isLeader {
                            showedcompanys = self.companys
                        } else {
                            showedcompanys = companys.filter { (json) -> Bool in
                                return self.needshows.contains(json.contents?["code"]?.rawString() ?? "")
                            }//需要展示的公司
                        }
                        var datas: [(String,String,String)] = []
                        let showedcodes = showedcompanys.map { (json) -> String in
                            return json.contents?["code"]?.rawString() ?? ""
                        }
                        self.numdatas.append(("","",0))
                        for key in data.keys {
                            if showedcodes.contains(key) {
                                let items = showedcompanys.filter { (json) -> Bool in
                                    return json.contents?["code"]?.rawString() == key
                                }
                                if items.count > 0{
                                    let item = items[0]
                                    let name = item.contents?["name"]?.rawString() ?? ""
                                    let count = data[key]?.int ?? 0
                                    let lbl = lround(Double(count) / Double(1000000))
                                    let lblstr = String(lbl).rmbformat
                                    datas.append((key,name,lblstr))
                                    self.numdatas.append((key,name,count))
                                }
                            }
                        }
                        var doubleArr: Array<Double> = []
                        let arr = data["xxx"]?.array ?? []
                        for i in arr {
                            if let val = i.int {
                                
                                let value = Double(val) / 1000000
                                
                                doubleArr.append(value)
                                
                            }
                        }
                        
                        loadBarData(array: doubleArr)
                        
                        showeddatas.append(contentsOf: datas)
                        let i = self.numdatas.reduce(0) { (result, element) -> Int in
                            return result + element.2
                        }
                        
                        if User.isLeader {
                            let total = lround(Double(i) / Double(1000000))
                            showeddatas.append(("0","合计",String(total).rmbformat))
                            moneyLabel.text = String(total).rmbformat + "(万元)"
                            self.numdatas.append(("","",total))
                        }
                    }
                    
                    self.tableheight.constant = CGFloat(40 * showeddatas.count + 20)
                    self.tableView.reloadData()
                    
                }
            } else {
                self.alert(json.contents?["errorMsg"]?.rawString())
            }
        }
        
        
        return name == "GetOrg" ? getOrgSuc : detail
    }
    
    override func param(for name: String) -> Dictionary<String,Any>{
        if name == "GetOrg" {
            return [:]
        } else {
            return ["Kvalue":key,"orgCode":selectedCompany,"searchDate":self.selectedDate]
        }
    }
    
    override func path(for name: String) -> String{
        
        return name == "GetOrg" ? GETORG : detailPath
        
    }
    
    override func method(for name: String) -> NetMethod{
        return .get
    }
    
    override var names: Array<String> {
        return ["GetOrg","Detail"]
    }
    
    //响应接口的有效性策略,如果参数不合格，则默认根据String提示
    override func strategy(for name: String) -> (Bool,String?,(()->Void)?){
        return (true,nil,nil)
    }
    
    func popalert() -> Void {
        let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
        
        for item in companys {
            let sheet = UIAlertAction.init(title: item.contents?["name"]?.rawString(), style: .default) { (action) in
                
                self.companyField.text = item.contents?["name"]?.rawString()
                
                self.selectedCompany = item.contents?["code"]?.rawString() ?? ""
                
                self.load(with: "Detail")
            }
            alert.addAction(sheet)
        }
        
        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        
        alert.addAction(cancel)
        
        self.present(alert, animated: true, completion: nil)
    }

}
